var express = require('express');
var router = express.Router();
require('./../util/util');
let User = require('./../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.post("/login",function (req,res,next) {
  let param = {
    userName:req.body.userName,
    userPwd:req.body.userPwd
  }
  User.findOne(param,function(err,doc){
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    }else{
      if(doc){
        res.cookie("userId",doc.userId,{
          path:'/',
          maxAge:1000*60*60
        });
        res.cookie("userName",doc.userName,{
          path:'/',
          maxAge:1000*60*60
        });
        // req.session.User = doc;  //需要安装插件
        res.json({
          status:"0",
           msg:'',
          result:{
            userName:doc.userName
          }
        })
      }
    }
  })
});
//登出接口
router.post("/logout",function(req,res,next){
  res.cookie("userId","",{
    path:"/",
    maxAge:-1  //生命周期
  })
  res.json({
    status:"0",
    msg:"",
    result:""
  })
  })


//验证登陆
router.get("/checkLogin",function(req,res,next){
  if(req.cookies.userId){
    res.json({
      status:'0',
      msg:'',
      result:req.cookies.userName
    })
  }else{
    res.json({
      status:'1',
      msg:'未登陆',
      result:''
    })
  }
});

//查询当前用户的购物车数据
router.get("/cartList",function(req,res,next){
 //由于已经拦截
  //req:从服务端去拿数据
  //res：写入服务端的数据
  let userId = req.cookies.userId;
  User.findOne({userId:userId},function(err,doc){
    if(err){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      })
    }else{
      if(doc){
        res.json({
          status:'0',
          msg:'',
          result:doc.cartList
        });
      }
    }
  })
});
//购物车删除功能
//购物车删除
router.post("/cartDel", function (req,res,next) {
  let userId = req.cookies.userId,productId = req.body.productId;
  User.update({
    userId:userId
  },{
    $pull:{  //删除cartList id相同的数据
      'cartList':{
        'productId':productId
      }
    }
  }, function (err,doc) {
    if(err){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      });
    }else{
      res.json({
        status:'0',
        msg:'',
        result:'suc'
      });
    }
  });
});
//购物车编辑，修改商品数量
router.post("/cartEdit",function(req,res,next){
  let userId = req.cookies.userId,
    productId = req.body.productId,
    checked = req.body.checked,
    productNum = req.body.productNum;
  User.update({"userId":userId,"cartList.productId":productId},{
    "cartList.$.productNum":productNum,
    "cartList.$.checked":checked
  },function(err,doc){
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    }else{
      res.json({
        status:'0',
        msg:'',
        result:'suc'
      });
    }
  })
});
//实现全选功能
router.post("/editCheckAll",function(req,res,next){
  let userId = req.cookies.userId,
     checkAll = req.body.checkAll?'1':'0';
  //拿到当前的用户对象
  User.findOne({userId:userId},function(err,user){
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    }else{
      if(user){
        user.cartList.forEach((item) =>{
          item.checked = checkAll;  //给item复值
        });
        user.save(function(err1,doc){
          if(err1){
            res.json({
              status: '1',
              msg: err1.message,
              result: ''
            });
          }else{
            res.json({
              status:'0',
              msg:'',
              result:'suc'
            });
          }
        })
      }
    }
  })
});

//查询用户地址接口
router.get("/addressList",function(req,res,next){
  let userId = req.cookies.userId;
  User.findOne({userId:userId},function(err,doc){
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    }else{
      res.json({
        status:'0',
        msg:'',
        result:doc.addressList
      });
    }
  })
});
//设置默认地址接口
router.post("/setDefault",function (req,res,next) {
  let userId = req.cookies.userId,
      addressId = req.body.addressId;
  if(!addressId){
    res.json({
      status: '1003',
      msg: 'addressId is null',
      result: ''
    });
  }else{
    User.findOne({userId:userId},function(err,doc){
      if(err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        });
      }else{
        let addressList = doc.addressList;
        addressList.forEach((item) =>{
          if(item.addressId == addressId){
            item.isDefault = true;  //相同设置为true
          }else{
            item.isDefault = false;  //不同设置为false
          }
        });
        doc.save(function (err1,doc1){
          if(err1){
            res.json({
              status: '1',
              msg: err1.message,
              result: ''
            });
          }else{
            res.json({
              status: '0',
              msg: '',
              result: ''
            });
          }
        })
      }
    });
  }
});

//删除地址接口
router.post("/delAddress", function (req,res,next) {
  let userId = req.cookies.userId,addressId = req.body.addressId;
  User.update({
    userId:userId
  },{
    $pull:{
      'addressList':{
        'addressId':addressId
      }
    }
  }, function (err,doc) {
    if(err){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      });
    }else{
      res.json({
        status:'0',
        msg:'',
        result:''
      });
    }
  });
});
//生成订单
router.post("/payMent",function(req,res,next){
  let userId = req.cookies.userId,
    addressId = req.body.addressId,
    orderTotal = req.body.orderTotal;
  User.findOne({userId:userId},function(err,doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      let address='',
          goodList=[];
      //获取当前用户的地址信息
      doc.addressList.forEach((item) =>{
        if(addressId == item.addressId){
          address =item;
        }
      });
      //获取用户购物车的购买商品
      doc.cartList.forEach((item) =>{
        if(item.checked=='1'){
          goodList.push(item);
        }
      });
      //生成订单号
      let platform ='622'; //假设一个平台
      let r1 = Math.floor(Math.random()*10); //随机数
      let r2 = Math.floor(Math.random()*10);
      let sysDate = new Date().Format('yyyyMMddhhmmss');
      let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
      let orderId = platform + r1 + sysDate + r2; //生产21位id号
      //创建订单
      let order ={
        orderId:orderId,
        orderTotal:orderTotal,
        addressInfo:address,
        goodList:goodList,
        orderStatus:'1',
        createDate:createDate
      };
      doc.orderList.push(order);
      //保存
      doc.save(function (err1,doc1){
        if(err1){
          res.json({
            status: '1',
            msg: err1.message,
            result: ''
          });
        }else{
          res.json({
            status: '0',
            msg: '',
            result:{
              orderId:order.orderId,
              orderTotal:order.orderTotal
            }
          });
        }
      })
    }
  })
});
//根据订单Id查询订单信息
router.get("/orderDetail",function(req,res,next){
  let userId = req.cookies.userId;
  let orderId = req.param("orderId");
  User.findOne({userId:userId},function(err,userInfo){
    if(err){
      res.json({
        status:'1',
        msg:err.message,
        result:''
      });
    }else{
      let orderList = userInfo.orderList;
      if(orderList.length > 0) {
        let orderTotal = 0;
        orderList.forEach((item) => {
          if(item.orderId == orderId) {
            orderTotal = item.orderTotal;
          }
        });
        if(orderTotal>0) {
          res.json({
            status: '0',
            msg:'',
            result: {
              orderId:orderId,
              orderTotal:orderTotal
            }
          })
        } else {
          res.json({
            status: '120002',
            msg: '无此订单',
            result: ''
          });
        }
      } else {
        res.json({
          status: '120001',
          msg: '当前用户未创建订单',
          result: ''
        });
      }
    }
  })
})
module.exports = router;
